package com.clip.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class DimensionCodeUtils {

	public static void encode(String contents, int width, int height, String imgPath) {  
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();  
        // 指定纠错等级  
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);  
        // 指定编码格式  
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");  
        try {  
            BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,  
                    BarcodeFormat.QR_CODE, width, height, hints);  
  
            MatrixToImageWriter  
                    .writeToFile(bitMatrix, "png", new File(imgPath));  
  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }

	public static String decode(File file) {  
		BufferedImage image;
        String content=null;
        try  
        {  
            if (file == null || file.exists() == false)  
            {  
                throw new Exception(" File not found:" + file.getPath());  
            }  
  
            image = ImageIO.read(file);  
  
            LuminanceSource source = new BufferedImageLuminanceSource(image);  
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));  
  
            Result result;  
  
            // 解码设置编码方式为：utf-8，  
            Hashtable hints = new Hashtable();  
            hints.put(DecodeHintType.CHARACTER_SET, "utf-8");  
  
            result = new MultiFormatReader().decode(bitmap, hints);  
  
            content=result.getText();  
  
        }  
        catch (Exception e)  
        {  
//            e.printStackTrace();  
        }finally{
        	return content;
        }
    }
}
